﻿using Core;
using Core.Data;
using Core.Domain.Common;
using Core.Domain.Localization;
using Data;
using Services.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace Services.Localization
{
    /// <summary>
    /// 本地化资源信息服务实现类
    /// </summary>
    public partial class LocalizationService : ILocalizationService
    {
        #region Fields

        private readonly IRepository<LocaleStringResource> _lsrRepository;
        private readonly IWorkContext _workContext;
        private readonly ILogger _logger;
        private readonly IDbContext _dbContext;
        private readonly CommonSettings _commonSettings;
        private readonly LocalizationSettings _localizationSettings;

        #endregion

        #region Ctor

        /// <summary>
        /// Ctor
        /// </summary>
        public LocalizationService(ILogger logger, IWorkContext workContext,
            IRepository<LocaleStringResource> lsrRepository, 
            IDataProvider dataProvider, IDbContext dbContext, CommonSettings commonSettings,
            LocalizationSettings localizationSettings)
        {
            this._logger = logger;
            this._workContext = workContext;
            this._lsrRepository = lsrRepository;
            this._dbContext = dbContext;
            this._commonSettings = commonSettings;
            this._dbContext = dbContext;
            this._commonSettings = commonSettings;
            this._localizationSettings = localizationSettings;
        }

        #endregion

        #region Methods

        /// <summary>
        /// 删除本地化资源
        /// </summary>
        /// <param name="localeStringResource">Locale string resource</param>
        public virtual void DeleteLocaleStringResource(LocaleStringResource localeStringResource)
        {
            if (localeStringResource == null)
                throw new ArgumentNullException("localeStringResource");

            _lsrRepository.Delete(localeStringResource);

        }

        /// <summary>
        /// 根据主键获取资源
        /// </summary>
        public virtual LocaleStringResource GetLocaleStringResourceById(int localeStringResourceId)
        {
            if (localeStringResourceId == 0)
                return null;

            return _lsrRepository.GetById(localeStringResourceId);
        }

        /// <summary>
        /// 根据资源名称获取资源
        /// </summary>
        public virtual LocaleStringResource GetLocaleStringResourceByName(string resourceName)
        {
                return GetLocaleStringResourceByName(resourceName);
        }


        /// <summary>
        /// 获取所有资源
        /// </summary>=
        public virtual IList<LocaleStringResource> GetAllResources()
        {
            var query = from l in _lsrRepository.Table
                        orderby l.ResourceName
                        select l;
            var locales = query.ToList();
            return locales;
        }

        /// <summary>
        /// 插入资源
        /// </summary>
        /// <param name="localeStringResource">Locale string resource</param>
        public virtual void InsertLocaleStringResource(LocaleStringResource localeStringResource)
        {
            if (localeStringResource == null)
                throw new ArgumentNullException("localeStringResource");
            
            _lsrRepository.Insert(localeStringResource);

        }

        /// <summary>
        /// 更新资源
        /// </summary>
        public virtual void UpdateLocaleStringResource(LocaleStringResource localeStringResource)
        {
            if (localeStringResource == null)
                throw new ArgumentNullException("localeStringResource");

            _lsrRepository.Update(localeStringResource);
        }

        /// <summary>
        /// 获取所有资源
        /// </summary>
        public virtual Dictionary<string, KeyValuePair<int, string>> GetAllResourceValues()
        {
            var query = from l in _lsrRepository.TableNoTracking
                        orderby l.ResourceName
                        select l;
            var locales = query.ToList();
            //format: <name, <id, value>>
            var dictionary = new Dictionary<string, KeyValuePair<int, string>>();
            foreach (var locale in locales)
            {
                var resourceName = locale.ResourceName.ToLowerInvariant();
                if (!dictionary.ContainsKey(resourceName))
                    dictionary.Add(resourceName, new KeyValuePair<int, string>(locale.Id, locale.ResourceValue));
            }
            return dictionary;
        }
        
        /// <summary>
        /// 根据资源值获取.
        /// </summary>
        public virtual string GetResource(string resourceKey,
            bool logIfNotFound = true, string defaultValue = "", bool returnEmptyIfNotFound = false)
        {
            string result = string.Empty;
            if (resourceKey == null)
                resourceKey = string.Empty;
            resourceKey = resourceKey.Trim().ToLowerInvariant();
            if (_localizationSettings.LoadAllLocaleRecordsOnStartup)
            {
                var resources = GetAllResourceValues();
                if (resources.ContainsKey(resourceKey))
                {
                    result = resources[resourceKey].Value;
                }
            }
            else
            {
                var query = from l in _lsrRepository.Table
                            where l.ResourceName == resourceKey
                            select l.ResourceValue;
                string lsr = query.FirstOrDefault();

                if (lsr != null)
                    result = lsr;
            }
            if (String.IsNullOrEmpty(result))
            {
                if (logIfNotFound)
                    _logger.Warning(string.Format("资源字符串 ({0}) 没有找到", resourceKey));
                
                if (!String.IsNullOrEmpty(defaultValue))
                {
                    result = defaultValue;
                }
                else
                {
                    if (!returnEmptyIfNotFound)
                        result = resourceKey;
                }
            }
            return result;
        }

        #endregion
    }
}
